<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋</title>
    <style>
        canvas {
            display: block;
            margin: 0 auto;
            border: 1px solid #000;
            background-color: #e5dcbc;

        }
    </style>
</head>
<body>

<canvas id="board" width="450" height="450"></canvas>
<script>
        const canvas = document.getElementById("board");
        const ctx = canvas.getContext("2d");
        const gridSize = 30;
        const rows = canvas.height / gridSize;
        const cols = canvas.width / gridSize;
        const board = new Array(rows).fill(null).map(() => new Array(cols).fill(0));

        let currentPlayer = 1;

        function drawGrid() {
            ctx.strokeStyle = "#000";
            for (let i = 0; i < rows; i++) {
                for (let j = 0; j < cols; j++) {
                    ctx.strokeRect(j * gridSize, i * gridSize, gridSize, gridSize);
                }
            }
        }

        function drawPiece(x, y, player) {
            ctx.beginPath();
            ctx.arc(x * gridSize + gridSize / 2, y * gridSize + gridSize / 2, gridSize / 2 - 5, 0, 2 * Math.PI);
            ctx.fillStyle = player === 1 ? "#000" : "#fff";
            ctx.fill();
            ctx.closePath();
        }

        function placePiece(x, y) {
            if (board[y][x] === 0) {
                board[y][x] = currentPlayer;
                drawPiece(x, y, currentPlayer);
                currentPlayer = currentPlayer === 1 ? 2 : 1;
            }
        }

        canvas.addEventListener("click", (e) => {
            const rect = canvas.getBoundingClientRect();
            const x = Math.floor((e.clientX - rect.left) / gridSize);
            const y = Math.floor((e.clientY - rect.top) / gridSize);
            placePiece(x, y);
        });

        drawGrid();

        function onSaveData() {
            return JSON.stringify(board);
        }

        function onRestoreData(data) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            drawGrid();
            const restoredBoard = JSON.parse(data);
            for (let y = 0; y < rows; y++) {
                for (let x = 0; x < cols; x++) {
                    const player = restoredBoard[y][x];
                    board[y][x] = player;
                    if (player !== 0) {
                        drawPiece(x, y, player);
                    }
                }
            }
        }
    </script>
</body>
</html>
